#include "myconfig.h"
#include <QDebug>
#include <QCoreApplication>

MyConfig::MyConfig(QObject *parent) : QObject(parent)
{
    QDir appDir = (QCoreApplication::applicationDirPath());
    m_dir = QDir(appDir).filePath("config/config.ini");

    ensureConfigFolderAndFile();
}

void MyConfig::ensureConfigFolderAndFile() {
    //检查并创建 config 文件夹
    //QDir configDir("config");
    QDir appDir = (QCoreApplication::applicationDirPath());
    QString dir = QDir(appDir).filePath("config");
    QDir configDir(dir);
    if (!configDir.exists()) {
        if (configDir.mkpath(".")) {
            qDebug() << "Config folder created successfully.";
        } else {
            qDebug() << "Failed to create config folder!";
            return;
        }
    }

    //检查并创建 config.ini 文件
    QFile configFile(m_dir);
    if (!configFile.exists()) {
        if (configFile.open(QIODevice::WriteOnly)) {
            configFile.close();
            qDebug() << "config.ini created successfully.";
        } else {
            qDebug() << "Failed to create config.ini!";
        }
    } else {
        qDebug() << "config.ini already exists.";
    }
}

// 从 config.ini 读取 16 个 WINDOW_CONFIG
QVector<WINDOW_CONFIG> MyConfig::loadWindowConfigs() {
    QVector<WINDOW_CONFIG> configs;
    //QSettings settings("config/config.ini", QSettings::IniFormat);
    QSettings settings(m_dir, QSettings::IniFormat);

    for (int i = 0; i < 16; ++i) {
        QString group = QString("WindowConfig_%1").arg(i);
        settings.beginGroup(group);

        WINDOW_CONFIG config;
        config.videoNum = settings.value("videoNum", 0).toInt(); // 默认值 0
        config.resourcesName = settings.value("resourcesName", "default").toString();
        config.ip = settings.value("ip", "127.0.0.1").toString();
        config.port = settings.value("port", 1234).toUInt();
        config.netCard = settings.value("netCard", "eth0").toString();

        configs.append(config);
        settings.endGroup();
    }

    qDebug() << "Configs loaded from config.ini";
    return configs;
}

void MyConfig::saveWindowConfigs(const QVector<WINDOW_CONFIG>& configs) {
    //QSettings settings("config/config.ini", QSettings::IniFormat);
    QSettings settings(m_dir, QSettings::IniFormat);

    for (int i = 0; i < configs.size(); ++i) {
        WINDOW_CONFIG config = configs[i];
        QString group = QString("WindowConfig_%1").arg(i); // 分组名称（如 WindowConfig_0）

        settings.beginGroup(group);
        settings.setValue("videoNum", config.videoNum);
        settings.setValue("resourcesName", config.resourcesName);
        settings.setValue("ip", config.ip);
        settings.setValue("port", config.port);
        settings.setValue("netCard", config.netCard);
        settings.endGroup();
    }

    settings.sync(); // 强制写入磁盘
    qDebug() << "Configs saved to config.ini";
}
